package queues;

import helpers.CrawlerHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tools.ant.taskdefs.condition.IsSet;

import admin.models.AutoSiteModel;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;

import entities.AutoSite;


public class AutoSiteLastestNews extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(AutoSiteLastestNews.class.getName());
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		log.setLevel(Level.FINE);
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		response.setContentType("text/plain");
		AutoSiteModel autoSiteModel = AutoSiteModel.getInstance();
		AutoSite autoSite = autoSiteModel.getSite(id);
		if (autoSite != null) {
			//Get lastest news
			List<String> lastestNews = CrawlerHelper.getLastestNews(autoSite);
			for (int i = 0; i < lastestNews.size(); i++) {
				DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
				Queue queue = QueueFactory.getDefaultQueue();
				String urlCrawler = "/queue-get-question/" + UrlHelper.getIdFromInfoUrl(lastestNews.get(i));
				
				log.info(urlCrawler);
				queue.add(TaskOptions.Builder.withUrl(urlCrawler).method(Method.GET));
			}
			
			//Update lastestScheduleSite
			autoSite.setLastestScheduleSite(new Date());
			autoSiteModel.insert(autoSite);
			
			response.getWriter().println("Get list new success auto id:" + id);
		} else {
			response.getWriter().println("Get list new unsuccess auto id:" + id);
		}
	}
}
